package com.itheima.controller;

import com.itheima.entity.Result;
import com.itheima.entity.StatusCode;
import com.itheima.pojo.Comment;
import com.itheima.service.CommentService;
import com.itheima.utile.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    IdWorker idWorker;
    @Autowired
    CommentService commentService;
    @Autowired
    RedisTemplate redisTemplate;
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") String id){
        Comment comment = commentService.get(id);
        return new Result(true, StatusCode.OK,"查询成功",comment);
    }
    @GetMapping("/article/{articleId}")
    public Result getArticle(@PathVariable("articleId") String articleId){
        List<Comment> comment = commentService.getArticle(articleId);
        return new Result(true, StatusCode.OK,"查询成功",comment);
    }
    @GetMapping
    public Result getAll(){
        List<Comment> comment = commentService.getAll();
        return new Result(true, StatusCode.OK,"查询成功",comment);
    }
    @PostMapping
    public Result save(@RequestBody Comment comment){
        long l = idWorker.nextId();
        comment.set_id(String.valueOf(l));
        comment.setPublishdate(new Date());
        commentService.save(comment);
        return new Result(true, StatusCode.OK,"新增成功");
    }
    @PutMapping
    public Result update(@RequestBody Comment comment){
        commentService.update(comment);
        return new Result(true, StatusCode.OK,"更新成功",comment);
    }
    //点赞功能
    @PutMapping("/thumbup/{_id}/{userId}")
    public Result thumbup(@PathVariable String _id,@PathVariable  String userId){
        //模拟获取到用户id

        BoundValueOperations boundValueOperations = redisTemplate.boundValueOps("thumbup_:" + userId + "_id:" + _id);

        if(boundValueOperations.get()==null){
            //数据库对应评论点赞数+1
            commentService.thumbup(_id);
           //没有点赞过,就就保存点赞记录
            redisTemplate.opsForValue().set("thumbup_:" + userId + "_id:" + _id,1);
            return new Result(true,StatusCode.OK,"点赞成功");
        }else{
            System.out.println(boundValueOperations.get().toString());
            return new Result(true,StatusCode.REMOTEERROR,"重复点赞");
        }
    }
}
